package one.stand.eureka.info;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.util.Date;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class LogWriter {
    private final static Map<String, LogInfo> logs = new ConcurrentHashMap<>();
    private FastDateFormat TIME = FastDateFormat.getInstance("HH:mm:ss");

    public void init(String key, String initStr) {
        logs.put(key, new LogInfo());
        info(key, initStr);
    }

    public void info(String key, String logStr) {
        print(0, key, logStr);
    }

    public void command(String key, String logStr) {
        print(3, key, logStr);
    }

    public void success(String key, String logStr) {
        print(1, key, logStr);
        print(4, key, "completed in " + logs.get(key).getRunningSecond() + "s<br/>" + "end is success");
    }

    public void error(String key, String logStr) {
        print(2, key, logStr);
        print(4, key, "completed in " + logs.get(key).getRunningSecond() + "s<br/>" + "end is error");
    }

    public String poll(String key) {
        return logs.get(key).getInfo().poll();
    }

    private void print(int flag, String key, String logStr) {
        if (StringUtils.isBlank(key)) return;
        if (logs.containsKey(key)) {
            String time = TIME.format(new Date());
            if (flag == 1) {
                logStr = "<br/><br/>" + time + "&nbsp;&nbsp;&nbsp;&nbsp;: <span style='color:green'>" + logStr + "</span>";
            } else if (flag == 2) {
                logStr = "<br/><br/>" + time + "&nbsp;&nbsp;&nbsp;&nbsp;: <span style='color:red'>" + logStr + "</span>";
            } else if (flag == 3) {
                logStr = "<br/>" + time + "&nbsp;&nbsp;&nbsp;&nbsp;: <span style='color:yellow'>" + logStr + "</span>";
            }
            logs.get(key).getInfo().add(logStr + "<br/>");
        }
    }

    @Data
    private class LogInfo {
        private long startTime = System.nanoTime();
        private Queue<String> info = new ConcurrentLinkedQueue<>();

        private long getRunningSecond() {
            return (System.nanoTime() - startTime) / 1000000000;
        }
    }
}